const express = require('express');
const multer = require('multer');
const XLSX = require('xlsx');
const path = require('path');

const app = express();
const upload = multer({ dest: 'uploads/' });

let data = [];

// 启用静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 上传文件接口（覆盖模式）
app.post('/upload', upload.array('files'), (req, res) => {
    data = []; // 清空原有数据

    req.files.forEach(file => {
        const workbook = XLSX.readFile(path.join(__dirname, file.path));
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];

        // 使用raw模式保留原始格式
        const newData = XLSX.utils.sheet_to_json(worksheet, { raw: true });

        // 过滤无效行（确保包含必要字段）
        const validData = newData.filter(item =>
            item.电话号码 && item.姓名 && item.物品名称 && item.单号
        );

        data = data.concat(validData);
    });

    res.json({
        message: `Successfully uploaded ${req.files.length} files`,
        totalRecords: data.length
    });
});

// 查询接口
app.get('/query', (req, res) => {
    const inputPhone = req.query.phone_number;
    if (!inputPhone) {
        return res.json({ error: '请输入电话号码' });
    }

    // 对输入的电话号码进行标准化处理
    const normalizedInput = inputPhone.replace(/\D/g, '').padStart(11, '0');

    const result = data.map(item => {
        // 提取原始电话号码并进行标准化
        let rawPhone = item.电话号码.toString().trim();
        rawPhone = rawPhone.replace(/\D/g, '').padStart(11, '0');

        return {
            ...item,
            标准化号码: rawPhone
        };
    }).filter(item => item.标准化号码 === normalizedInput);

    if (result.length === 0) {
        return res.json({ error: '未找到匹配记录' });
    }

    res.json(result.map(item => ({
        姓名: item.姓名,
        物品名称: item.物品名称,
        单号: item.单号
    })));
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});